var amqp = require('amqplib/callback_api');

var args = process.argv.slice(2);

if (args.length == 0) {
    console.log("Usage: rpc_client.js num");
    process.exit(1);
}

amqp.connect('amqp://localhost', function (err, conn) {
    if (err) { exit(err); }
    conn.createChannel(function (err, ch) {
        if (err) { exit(err); }
        ch.assertQueue('', {exclusive: true}, function (err, q) {
            if (err) { exit(err); }

            var corr = generateUuid();
            var num = parseInt(args[0]);
    
            console.log(' [x] Requesting fib(%d)', num);

            // 准备获取返回值
            ch.consume(q.queue, function (msg) {
                if (msg.properties.correlationId == corr) {
                    console.log(' [.] Got %s', msg.content.toString());
                    setTimeout(() => {
                        conn.close(); process.exit(0);
                    }, 500);
                }
            }, {noAck: true});

            // 发送请求
            ch.sendToQueue('rpc_queue', new Buffer(num.toString()), {
                correlationId: corr,
                replyTo: q.queue
            })
        });
    });
});

function exit(err) {
    console.log(err);
    process.exit(1);
}

function generateUuid() {
    return Math.random().toString() +
        Math.random().toString() +
        Math.random().toString();
}